package com.rgst.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rgst.anno.DontLogin;
import com.rgst.dao.entity.User;
import com.rgst.dao.repository.UserRepository;
import com.rgst.dto.Result;
import com.rgst.dto.UserDto;
import com.rgst.utils.CacheUtils;
import com.rgst.utils.Md5SaltTool;
import com.rgst.vo.RgstUserVo;

/**
 * Created by tancw on 2019/11/20.
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserRepository userRepository;

    @Value("${login.error.max.times}")
    private Integer loginErrorMaxTimes = 5;


    @RequestMapping("/toLogin")
    @DontLogin
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    @DontLogin
    @ResponseBody
    public Result login(HttpServletRequest request, RgstUserVo rgstUserVo) {
        Assert.notNull(rgstUserVo.getMobile(), "手机号不能为空");
        Assert.notNull(rgstUserVo.getPassword(), "密码不能为空");
        String mobile = rgstUserVo.getMobile();
        Integer useTimes = (Integer) CacheUtils.getOrDefault(mobile, 0);
        if (useTimes >= loginErrorMaxTimes) {
            return Result.error("请稍后重试!");
        }
        try {
            User user = userRepository.findByMobile(mobile);
            Assert.notNull(user, "user error");
            boolean isRight = Md5SaltTool.validPassword(rgstUserVo.getPassword(), user.getPassword());
            if (isRight) {
                UserDto userDto = new UserDto();
                BeanUtils.copyProperties(user, userDto);
                setSessionUser(request, userDto);
                return Result.success("main");
            } else {
                CacheUtils.set(mobile, useTimes + 1);
            }
        } catch (Exception e) {
            CacheUtils.set(mobile, useTimes + 1);
            e.printStackTrace();
        }
        Integer restTimes = loginErrorMaxTimes - (useTimes + 1);
        return Result.error(restTimes > 0 ? "手机号或密码错误,剩余次数" + restTimes + "次!" : "请稍后重试!");
    }

}
